package main

import (
	"log"
	"math/rand"
	"sync"
	"time"
)

//协程池

var wg sync.WaitGroup

type Task struct {
	ID         int
	JobID      int
	Status     string
	CreateTime time.Time
}

func (t *Task) Run() {
	sleep := rand.Intn(1000)
	time.Sleep(time.Duration(sleep) * time.Millisecond)
	t.Status = "Completed"
}

//任务的数量，即使用多少goroutine执行任务
const workerNum = 3

func RunTaskWithPool() {
	wg.Add(workerNum)

	//创建容量为10的buffered channel
	taskQueue := make(chan *Task, 10)

	log.Printf("start %d goroutine", workerNum)
	//激活goroutine，执行任务
	for workID := 1; workID <= workerNum; workID++ {
		go worker(taskQueue, workID)
	}

	//生成消息
	produceTask(taskQueue)

	time.Sleep(5 * time.Second)
	close(taskQueue)
	wg.Wait()

}

func produceTask(out chan<- *Task) {
	//将待执行任务放进buffered channel，共计15个任务
	for i := 1; i <= 15; i++ {
		out <- &Task{
			ID:         i,
			JobID:      100 + i,
			Status:     "",
			CreateTime: time.Now(),
		}
		log.Printf("produce work %d to channel\n", i)
		log.Printf("len of channel: %d", len(out))
	}
}

//从buffered channel读取任务，执行任务
func worker(in <-chan *Task, workID int) {
	defer wg.Done()
	for v := range in {
		log.Printf("Worker%d: recv a request: TaskID:%d, JobID:%d\n", workID, v.ID, v.JobID)
		v.Run()
		log.Printf("Worker%d: Complete for TaskID:%d, JobID:%d\n", workID, v.ID, v.JobID)
	}
}

func main() {
	RunTaskWithPool()
}
